<template>
  <div id="app">
    <div>{{ message }}</div>
    <div class="intro">
      <!-- <p v-html="intro"></p> -->
      <p style="color: yellow">
        你的待办事项有{{ highTasks }}项重要，{{ normalTasks }}项一般，{{
          lowTasks
        }}项低。
      </p>
      <img :src="imgUrl" alt="avatar" />
    </div>
    <!-- <div>{{ getHighTasks() }} 个重要事项</div> -->
    <!-- <div>{{ fullName }} <button @click="fullName = 'Thoms Wang'">修改名字</button></div> -->
    <!-- <button @click="obj.count++">Count++</button>
    <button @click="obj.state =!obj.state">Toggle State</button>
    <button @click="obj.state.status =!obj.state.status">Deep State</button> -->
    <hr />
    <input
      type="text"
      class="taskInput"
      v-model="newTask"
      placeholder="把计划写下来吗?"
      @keyup.enter="addTask"
    />
    <button @click="addTask">添加</button>
    <div class="priority">
      <div>
        <input type="radio" value="重要" v-model="priority" />重要
        <input type="radio" value="一般" v-model="priority" />一般
        <input type="radio" value="低" v-model="priority" />低
      </div>
      <p>任务优先级: {{ priority }}</p>
    </div>
    <div>任务列表</div>
    <template v-if="tasks.length > 0">
      <ul>
        <TransitionGroup
          tag="ul"
          :css="false"
          @before-enter="onBeforeEnter"
          @enter="onEnter"
          @leave="onLeave"
        >
          <li v-for="(task, index) in tasks" :key="index" :data-index="index">
            <div class="yuan" :style="getStyleByTask(task)"></div>
            <div class="task-text" v-if="!task.editing">{{ task.text }}</div>
            <input v-else type="text" v-model="task.text" />

            <div class="actions">
              <span class="edit" @click="toggleEdit(task)">
                {{ task.editing ? '保存' : '编辑' }}
              </span>
              <span class="delete" @click="deleteTask(index)">删除</span>
            </div>
          </li>
        </TransitionGroup>
      </ul>
    </template>
    <template v-else>
      <p>没有数据！</p>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { gsap } from 'gsap'

const newTask = ref('')
const priority = ref('一般')
const tasksCopy = ref([
  {
    text: '学习前端基础HTML5/CSS3/JavaScript',
    editing: false,
    priority: '一般',
  },
  { text: '学习Vue.JS的基础知识', editing: false, priority: '重要' },
  { text: '学习前端构建工具', editing: false, priority: '一般' },
  { text: '学习前端UI构建', editing: false, priority: '重要' },
  { text: '学习前端状态管理', editing: false, priority: '一般' },
  { text: '学习前端路由管理', editing: false, priority: '一般' },
  { text: '学习前端网络管理', editing: false, priority: '低' },
  { text: '综合案例实战', editing: false, priority: '一般' },
])
const tasks = ref([
  {
    text: '学习前端基础HTML5/CSS3/JavaScript',
    editing: false,
    priority: '一般',
  },
  { text: '学习Vue.JS的基础知识', editing: false, priority: '重要' },
  { text: '学习前端构建工具', editing: false, priority: '一般' },
  { text: '学习前端UI构建', editing: false, priority: '重要' },
  { text: '学习前端状态管理', editing: false, priority: '一般' },
  { text: '学习前端路由管理', editing: false, priority: '一般' },
  { text: '学习前端网络管理', editing: false, priority: '低' },
  { text: '综合案例实战', editing: false, priority: '一般' },
])
const message = '你的代办事项'
// const intro = "<p style='color:yellow'>待办事项是一款任务管理工具，用户可以用它方便地组织和安排事务，把要做的事情一项一项地列出来，避免忘记。它具有以下功能</p>";
const imgUrl = './images/user.png'

// watch(newTask, (newVal, oldVal) => {
//   console.log("newTask changed:", newVal, oldVal);
// })

// 多数据源的监听
// watch([newTask, tasks.value], ([newTask, tasks]) => {
//   console.log("newTask tasks changed:", newTask, tasks);
// })

// watch(tasks.value, (newVal, oldVal) => {
//   console.log("tasks changed:", newVal, oldVal);
// })

// 响应式对象
// const obj = reactive({ count: 0, state: { status: true } })

// watch(obj, (newValue, oldValue) => {
//   // 在嵌套的属性变更时触发
//   // 注意：`newValue` 此处和 `oldValue` 是相等的
//   // 因为它们是同一个对象！
//   console.log("obj changed:", newValue, oldValue);
// })

// watch(
//   () => obj.state,
//   () => {
//     // 仅当 obj.state 被替换时触发
//     console.log("obj.state changed:", obj.state);
//   }
// )

// 深度监听
// watch(
//   () => obj.state,
//   (newValue, oldValue) => {
//     // 仅当 obj.state 被替换时触发
//     console.log("obj.state changed:", newValue, oldValue);
//   },
//   { deep: true }
// )

// 错误，因为 watch() 得到的参数是一个 number
// watch(obj.count, (count) => {
//   console.log(`Count is: ${count}`)
// })
// watch(() => obj.count, (count) => {
//   console.log(`Count is: ${count}`)
// })
// 副作用：watch实际应用场景，不仅是捕获数据的变化，而且是要进行相应的处理。

function onBeforeEnter(el) {
  el.style.opacity = 0
  el.style.height = 0
}

function onEnter(el, done) {
  gsap.to(el, {
    opacity: 1,
    height: '1.6em',
    delay: el.dataset.index * 0.15,
    onComplete: done,
  })
}

function onLeave(el, done) {
  gsap.to(el, {
    opacity: 0,
    height: 0,
    delay: el.dataset.index * 0.15,
    onComplete: done,
  })
}

watch(newTask, (newVal, oldVal) => {
  console.log('newTask changed:', newVal, oldVal)
  if (newVal.trim() !== '') {
    // 过滤掉已删除的任务
    tasks.value = tasksCopy.value.filter(task => task.text.includes(newVal))
  } else {
    // tasks.value = [...tasksCopy.value];
    tasks.value = JSON.parse(JSON.stringify(tasksCopy.value))
  }
})

const getStyleByTask = task => {
  switch (task.priority) {
    case '重要':
      return { backgroundColor: 'red' }
    case '低':
      return { backgroundColor: 'gray' }
    default:
      return { backgroundColor: 'green' }
  }
}
// 可写计算属性
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
  // getter
  get() {
    return firstName.value + ' ' + lastName.value
  },
  // setter
  set(newValue) {
    // 注意：我们这里使用的是解构赋值语法
    ;[firstName.value, lastName.value] = newValue.split(' ')
  },
})

// 通过函数实现计算属性，在输入框输入内容就会不断的被调用
const getHighTasks = () => {
  console.log('getHighTasks called')
  return tasks.value.filter(task => task.priority === '重要').length
}
// 计算属性
const highTasks = computed(() => {
  console.log('highTasks called')
  return tasks.value.filter(task => task.priority === '重要').length
})

const lowTasks = computed(() => {
  return tasks.value.filter(task => task.priority === '低').length
})

const normalTasks = computed(() => {
  return tasks.value.filter(task => task.priority === '一般').length
})
const addTask = () => {
  if (newTask.value.trim() !== '') {
    tasks.value.push({
      text: newTask.value,
      editing: false,
      priority: priority.value,
    })
    newTask.value = ''
    priority.value = '一般'
  }
  tasksCopy.value = [...tasks.value]
}

const toggleEdit = task => {
  task.editing = !task.editing
}

const deleteTask = index => {
  if (confirm('确定要删除这个任务吗？')) {
    tasks.value.splice(index, 1)
  }
}
</script>

<style scoped></style>
